package com.zdkj.subway.check.controller.subwayRat.fareDifferencesInAudit;

import cn.hutool.core.collection.CollectionUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.zdkj.common.core.util.R;
import com.zdkj.common.log.annotation.SysLog;
import com.zdkj.common.security.service.PigxUser;
import com.zdkj.common.security.util.SecurityUtils;
import com.zdkj.subway.check.controller.CommonController;
import com.zdkj.subway.check.entity.*;
import com.zdkj.subway.check.enums.ResultDetailMsg;
import com.zdkj.subway.check.mapper.*;
import com.zdkj.subway.check.result.Result;
import com.zdkj.subway.check.service.impl.subwayRat.fareDifferencesInAudit.FareDifferencesInAuditServiceImpl;
import com.zdkj.subway.check.util.DateFormat;
import com.zdkj.subway.check.util.JdbcUtil;
import com.zdkj.subway.check.util.LineOrStation;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.sql.SQLException;
import java.text.ParseException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 报表差错信息
 */
@RestController
@RequestMapping("/check")
@Api(value = "check",tags = "TVM单台设备审核")
@Slf4j
public class FareDifferencesInAuditController {

    @Autowired
    private FareDifferencesInAuditServiceImpl fareDifferencesInAuditService;
    @Resource
    FareDifferencesInAuditMapper fareDifferencesInAuditMapper;
    @Resource
    SwAuTvmAmountDefferenceMapper swAuTvmAmountDefferenceMapper;
    @Resource
    SwAuTvmCashAmountHierarchyDifferenceMapper swAuTvmCashAmountHierarchyDifferenceMapper;
    @Resource
    SwAuTvmAmountDefferenceLogMapper swAuTvmAmountDefferenceLogMapper;
    @Autowired
    private CommonController commonController;
    @Resource
    private SwStReportErrorAlterAppayMapper swStReportErrorAlterAppayMapper;
    @Resource
    private SwStReportErrorAlterAppayDetailMapper swStReportErrorAlterAppayDetailMapper;

    /**
     *
     * @param page
     * @param param 列表查询传入的参数
     * @return
     * @throws ParseException
     */
    @ApiOperation(value = "TVM单台设备审核查询", notes = "TVM单台设备审核查询")
    @RequestMapping("/getFareDifferencesInAudit")
    public R getCashboxUninstallList(com.baomidou.mybatisplus.extension.plugins.pagination.Page page, @RequestParam Map<String, Object> param) throws ParseException {
        PigxUser user = SecurityUtils.getUser();
        //区分是否是线网人员
        if(user.getBelongToLine()){
            List lineList = LineOrStation.getmanagementLine();
            param.put("lines",lineList);
        }else{
            List lineList = LineOrStation.getLineOrManagementLine();
            param.put("lines",lineList);
        }
        Map<String,String> map = JSONObject.parseObject(JSONObject.toJSONString(param), Map.class);
        Map params = new HashMap();
        if(null != map.get("param")){
            params = JSONObject.parseObject(map.get("param"), Map.class);
        }
        //查询TVM票款差异审核表
        IPage<FareDifferencesInAudit> cashboxUninstallList = fareDifferencesInAuditService.getFareDifferencesInAudit(page,param);
        //获取分页列表
        List<FareDifferencesInAudit> records = cashboxUninstallList.getRecords();
        Date curr_date = new Date();
        String currdateStr = DateFormat.date_ex_str(curr_date,"yyyy-MM-dd")+" 00:00:00";
        Date currdate = DateFormat.panDuanDate(currdateStr);
        for (FareDifferencesInAudit record : records) {
            //线路+站点+TVM编号+收益日期+报表名称（TVM钱箱清点记录 or 手工清出 or 补币）+（钱箱类型为空的）+ 除了审批不通过    查找TVM审核（三者任何一个为不是已完成，显示为未完成）
            List<SwStReportErrorAlterApply> applies =
                    swStReportErrorAlterAppayMapper.selectList(Wrappers.<SwStReportErrorAlterApply>lambdaQuery()
                    .eq(SwStReportErrorAlterApply::getLineCode, record.getLineCode()).eq(SwStReportErrorAlterApply::getStationCode, record.getStationCode())
				    .eq(SwStReportErrorAlterApply::getTvmCode, record.getTvmCode())  //能加TVM编号，涉及到补币和手工清出再单独查问题
                    .eq(SwStReportErrorAlterApply::getReprotTime, DateFormat.dateTOLocalDate(record.getRecordTime()))
                    .eq(SwStReportErrorAlterApply::getCashboxType, "").in(SwStReportErrorAlterApply::getReportNameId, 5, 6, 7)
				    .eq(SwStReportErrorAlterApply::getDelFlag, "0")
                    .ne(SwStReportErrorAlterApply::getIsModify,"1")
                    .ne(SwStReportErrorAlterApply::getCheckStatus,"4"));
            List<SwStReportErrorAlterApply> collect = applies.stream().filter(s -> {
                if (s.getNoticeTime() != null) {
                    //利用Calendar 实现 Date日期 通知时间+期限 < 当前时间 过滤掉
                    Date date = null;
                    try {
                        //取到年月日
                        String dateStr = DateFormat.date_ex_str(s.getNoticeTime(),"yyyy-MM-dd")+" 00:00:00";
                        Date noticedate = DateFormat.panDuanDate(dateStr);
                        date = DateFormat.date_add_or_sub_days(noticedate, s.getModifyLimitTime());
                    } catch (ParseException e) {
                        e.printStackTrace();
                    }
                    boolean b = date.compareTo(currdate) >= 0;
                    return b;

                }
                return true;
            }).collect(Collectors.toList());

			//查补币和手工清出问题
			 List<SwStReportErrorAlterApply> appliesHand =
                    swStReportErrorAlterAppayMapper.selectList(Wrappers.<SwStReportErrorAlterApply>lambdaQuery()
                    .eq(SwStReportErrorAlterApply::getLineCode, record.getLineCode()).eq(SwStReportErrorAlterApply::getStationCode, record.getStationCode())
				    //.eq(SwStReportErrorAlterApply::getTvmCode, record.getTvmCode())  //不能加TVM编号，涉及到补币和手工清出
                    .eq(SwStReportErrorAlterApply::getReprotTime, DateFormat.dateTOLocalDate(record.getRecordTime()))
                    .eq(SwStReportErrorAlterApply::getCashboxType, "").in(SwStReportErrorAlterApply::getReportNameId, 6, 7)
				    .eq(SwStReportErrorAlterApply::getDelFlag, "0")
                    .ne(SwStReportErrorAlterApply::getIsModify,"1")
                    .ne(SwStReportErrorAlterApply::getCheckStatus,"4"));
            List<SwStReportErrorAlterApply> collectHand = appliesHand.stream().filter(s -> {
                if (s.getNoticeTime() != null) {
                    //利用Calendar 实现 Date日期 通知时间+期限 < 当前时间 过滤掉
                    Date date = null;
                    try {
                        //取到年月日
                        String dateStr = DateFormat.date_ex_str(s.getNoticeTime(),"yyyy-MM-dd")+" 00:00:00";
                        Date noticedate = DateFormat.panDuanDate(dateStr);
                        date = DateFormat.date_add_or_sub_days(noticedate, s.getModifyLimitTime());
                    } catch (ParseException e) {
                        e.printStackTrace();
                    }
                    boolean b = date.compareTo(currdate) >= 0;
                    return b;

                }
                return true;
            }).collect(Collectors.toList());
            //都不是null 说明未完成
            if(CollectionUtil.isNotEmpty(collect) || CollectionUtil.isNotEmpty(collectHand)){
                //0代表待修改
                record.setIsModify("0");
            }else {
                //1代表已完成
                record.setIsModify("1");
            }
        }
        cashboxUninstallList.setRecords(records);
        return R.ok(cashboxUninstallList);
    }

    /**
     * 设置差异原因
     * @param param
     * @return 差异原因
     */
    @ApiOperation(value = "设置差异原因",notes = "设置差异原因")
    @RequestMapping("/updateDifferences")
    public Result updateDifferences(@RequestParam Map<String,String> param){
        Result result=new Result(ResultDetailMsg.OK);
        fareDifferencesInAuditService.updateDifferences(param);
        return result;
    }

    /**
     * 一键审核
     * @param param ids
     * @return
     */
    @ApiOperation(value = "一键审核",notes = "一键审核")
    @RequestMapping("/updateAuditStatusDefference")
    public Result updateAuditStatusDefference(@RequestParam Map<String,String> param){
        Result result=new Result(ResultDetailMsg.OK);
		PigxUser user = SecurityUtils.getUser();
		//审核处理
        fareDifferencesInAuditService.updateAuditStatusDefference(param,user);
        return result;
    }
    /**
     * TVM票款差异审核-加入通知
     * @param param ids
     * @return
     */
    @ApiOperation(value = "TVM票款差异审核-加入通知",notes = "TVM票款差异审核-加入通知")
    @RequestMapping("/jiaRuNoticeTvm")
    public Result jiaRuNoticeTvm(@RequestBody Map<String,Object> param) throws Exception {
        Result result=new Result(ResultDetailMsg.OK);
        //加入通知
        fareDifferencesInAuditService.jiaRuNoticeTvm(param);
        //给车站发代办
        commonController.innerBatch(param);
        return result;
    }

    /**
     * 加入结账单据协查或者单台设备差异协查
     * @param param 1为结账单据协查 2为单台设备协查
     * @return
     */
    @ApiOperation(value = "加入结账单据协查或者单台设备差异协查",notes = "加入结账单据协查或者单台设备差异协查,1为结账单据协查 2为单台设备协查")
    @RequestMapping("/insertCheckTheDocumentsInvestigation")
    public Result insertCheckTheDocumentsInvestigation(@RequestParam Map<String,String> param){
        Result result=new Result(ResultDetailMsg.OK);
        //加入结账单据协查或者单台设备差异协查
        fareDifferencesInAuditService.insertCheckTheDocumentsInvestigation(param);
        return result;
    }

    /**
     * 差异审核主表替换来源值
     * @param ids
     * @return
     */
    @ApiOperation(value = "差异审核主表替换来源值",notes = "差异审核主表替换来源值")
    @RequestMapping("/replaceSwAuTvmAmountDefference")
    public Result replaceSwAuTvmAmountDefference(String ids/*,SwAuTvmCashAmountHierarchyDifference swAuTvmCashAmountHierarchyDifference*/,String tableDataSource){
        Result result=new Result(ResultDetailMsg.OK);
        try {
            for(String id:ids.split(",")){
                SwAuTvmCashAmountHierarchyDifference swAuTvmCashAmountHierarchyDifference = swAuTvmCashAmountHierarchyDifferenceMapper.selectById(Integer.parseInt(id));
                SwAuTvmAmountDefference fareDifferencesInAudit = swAuTvmAmountDefferenceMapper.selectById(swAuTvmCashAmountHierarchyDifference.getRelationSourceId());
                String auditStatus = fareDifferencesInAudit.getAuditStatus();
                //已经审核的数据不能一键替换
                //已经审核的数据
                if(StringUtils.isNotEmpty(auditStatus) && auditStatus.equals("1")){
                    result.setResult(ResultDetailMsg.CHECK_UPDATE_ERROR);
                    result.setMsg("收入已审核，不能再做一键替换");
                    return result;
                }
//            FareDifferencesInAudit fareDifferencesInAudit=new FareDifferencesInAudit();
                fareDifferencesInAudit.setId(swAuTvmCashAmountHierarchyDifference.getRelationSourceId());
                //区分数据来源 sc、lc、acc
                if("2".equals(tableDataSource)){ //sc
                    fareDifferencesInAudit.setScCashRecharge(swAuTvmCashAmountHierarchyDifference.getReplyRechargeMoney());
                    fareDifferencesInAudit.setScCashReturn(swAuTvmCashAmountHierarchyDifference.getReplyErrorReturnMoney());
                    fareDifferencesInAudit.setScCashSellTicket(swAuTvmCashAmountHierarchyDifference.getReplySaleMoney());
                }else if("3".equals(tableDataSource)){//sc-lc
                    fareDifferencesInAudit.setScCashRecharge(swAuTvmCashAmountHierarchyDifference.getReplyRechargeMoney());
                    fareDifferencesInAudit.setScCashReturn(swAuTvmCashAmountHierarchyDifference.getReplyErrorReturnMoney());
                    fareDifferencesInAudit.setScCashSellTicket(swAuTvmCashAmountHierarchyDifference.getReplySaleMoney());

                }else if("4".equals(tableDataSource)){//lc-ACC
                    fareDifferencesInAudit.setLcCashRecharge(swAuTvmCashAmountHierarchyDifference.getReplyRechargeMoney());
                    fareDifferencesInAudit.setLcCashReturn(swAuTvmCashAmountHierarchyDifference.getReplyErrorReturnMoney());
                    fareDifferencesInAudit.setLcCashSellTicket(swAuTvmCashAmountHierarchyDifference.getReplySaleMoney());

                    //新加的对比回馈字段为ACC
                    fareDifferencesInAudit.setAccCashRecharge(swAuTvmCashAmountHierarchyDifference.getReplyComparativeRechargeMoney());
                    fareDifferencesInAudit.setAccCashReturn(swAuTvmCashAmountHierarchyDifference.getReplyComparativeErrorReturnMoney());
                    fareDifferencesInAudit.setAccCashSellTicket(swAuTvmCashAmountHierarchyDifference.getReplyComparativeSaleMoney());
                }
                if((fareDifferencesInAudit.getDataSource().equals("4") || fareDifferencesInAudit.getDataSource().equals("3") || fareDifferencesInAudit.getDataSource().equals("2")) &&
                        tableDataSource.equals(fareDifferencesInAudit.getDataSource())){
                    BigDecimal subtract = swAuTvmCashAmountHierarchyDifference.getReplyRechargeMoney().add(swAuTvmCashAmountHierarchyDifference.getReplySaleMoney()).add(swAuTvmCashAmountHierarchyDifference.getReplyErrorReturnMoney());
                    fareDifferencesInAudit.setSystemMoney(subtract);
                   // fareDifferencesInAudit.setDiffMoney(subtract.subtract(fareDifferencesInAudit.getActualMoney().subtract(fareDifferencesInAudit.getSupplementMoney().add(fareDifferencesInAudit.getHandOutMoney()))));
                    //实点-系统
                    fareDifferencesInAudit.setDiffMoney(fareDifferencesInAudit.getActualMoney().subtract(subtract));
                }
                int i = swAuTvmAmountDefferenceMapper.updateById(fareDifferencesInAudit);

                swAuTvmCashAmountHierarchyDifference.setReplaceStatus("1");
                swAuTvmCashAmountHierarchyDifferenceMapper.updateById(swAuTvmCashAmountHierarchyDifference);
            }
        }catch (Exception e){
            log.error("{}",e);
            result.setResult(ResultDetailMsg.CHECK_UPDATE_ERROR);
            result.appendMsg("票款差异审核主表替换失败！");
        }
        return result;
    }

    /**
     * 加入层级差异协查
     * @param param ids,层级类型
     * @return
     */
    @ApiOperation(value = "加入层级差异协查",notes = "加入层级差异协查,sc-lc,lc-acc")
    @RequestMapping("/insertSwAuTvmCashAmountHierarchyDifference")
    public Result insertSwAuTvmCashAmountHierarchyDifference(@RequestParam Map<String,String> param){
        Result result=new Result(ResultDetailMsg.OK);
        //加入层级差异协查
        fareDifferencesInAuditService.insertSwAuTvmCashAmountHierarchyDifference(param);
        return result;
    }

    /**
     * 票款差异列表-刷新按钮-从接口表取数据
     * @param param
     * @return
     */
    @ApiOperation(value = "票款差异列表-刷新按钮-从接口表取数据",notes = "票款差异列表-刷新按钮-从接口表取数据")
    @RequestMapping("/syncSystemAmounts")
    public Result syncSystemAmounts(@RequestParam  Map<String,Object> param)throws Exception{
        Result result=new Result(ResultDetailMsg.OK);
        String dataSource = String.valueOf(param.get("dataSource"));
        Map<String,Object> row = JSONObject.parseObject(String.valueOf(param.get("row")),Map.class);
        Object incomeSettleBeginTime = row.get("incomeSettleBeginTime");
        Object incomeSettleEndTime = row.get("incomeSettleEndTime");
        String startTime = DateFormat.ex_strDate_to_date(String.valueOf(incomeSettleBeginTime), "yyyyMMdd");
        String endTime = DateFormat.ex_strDate_to_date(String.valueOf(incomeSettleEndTime), "yyyyMMdd");

//        String bookdate= DateFormat.ex_strDate_to_date(row.get("recordTime")+"","yyyyMMdd");
        String type = "";
        if("2".equals(dataSource)){
            type = "sc";
        }else if("3".equals(dataSource)){
            type = "lc";
        }else if("4".equals(dataSource)){
            type = "acc";
        }

		//根据不同类型从接口获取数据
        List<Map<String, Object>> resp = JdbcUtil.exeSqlQuery("select ifnull(sum(sale_txnamtall),0) sale_txnamtall, ifnull(sum(recharge_txnamtall),0) recharge_txnamtall,ifnull(sum(refund_txnamtall),0) refund_txnamtall from "+type+"_fare_statistics " +
                "where equipmenttype='1'and station_equipment_number='" + String.valueOf(row.get("tvmCode")) + "'" +
                " and (paymethod='0' or paymethod='1' or paymethod='10' OR paymethod is NULL or paymethod like '%3130%') and lineid='" + String.valueOf(row.get("lineCode")) +"'" +
                " and station_number='" + String.valueOf(row.get("stationCode")) +"'" +
                " and bookdate >='" +startTime+"' and bookdate <='"+endTime+"'", "sale_txnamtall,recharge_txnamtall,refund_txnamtall");
        if(null != resp && 0 != resp.size()){
            Map<String, Object> map = resp.get(0);
            ///发售交易金额
            BigDecimal sale_txnamtall = BigDecimal.valueOf(Long.valueOf(String.valueOf(map.get("sale_txnamtall"))));
            //充值交易金额
            BigDecimal recharge_txnamtall = BigDecimal.valueOf(Long.valueOf(String.valueOf(map.get("recharge_txnamtall"))));
            //退款交易金额
            BigDecimal refund_txnamtall = BigDecimal.valueOf(Long.valueOf(String.valueOf(map.get("refund_txnamtall"))));
            SwAuTvmAmountDefference swAuTvmAmountDefference = new SwAuTvmAmountDefference();
            swAuTvmAmountDefference.setId(Integer.valueOf(String.valueOf(row.get("id"))));
            //区分数据来源
            if("2".equals(dataSource)){
                swAuTvmAmountDefference.setScCashSellTicket(sale_txnamtall);
                swAuTvmAmountDefference.setScCashRecharge(recharge_txnamtall);
                swAuTvmAmountDefference.setScCashReturn(refund_txnamtall);
            }else if("3".equals(dataSource)){
                swAuTvmAmountDefference.setLcCashSellTicket(sale_txnamtall);
                swAuTvmAmountDefference.setLcCashRecharge(recharge_txnamtall);
                swAuTvmAmountDefference.setLcCashReturn(refund_txnamtall);
            }else if("4".equals(dataSource)){
                swAuTvmAmountDefference.setAccCashSellTicket(sale_txnamtall);
                swAuTvmAmountDefference.setAccCashRecharge(recharge_txnamtall);
                swAuTvmAmountDefference.setAccCashReturn(refund_txnamtall);
            }
            swAuTvmAmountDefferenceMapper.updateById(swAuTvmAmountDefference);
        }
        SwAuTvmAmountDefference swAuTvmAmountDefference1 = swAuTvmAmountDefferenceMapper.selectById((Integer) row.get("id"));
        result.setData(swAuTvmAmountDefference1);
        return result;
    }

    /**
     * 票款差异列表-数据来源替换按钮-替换数据来源
     * @param swAuTvmAmountDefference
     * @return
     */
    @ApiOperation(value = "票款差异列表-数据来源替换按钮-替换数据来源",notes = "票款差异列表-数据来源替换按钮-替换数据来源")
    @RequestMapping("/replaceCengJiDatasourceSwAuTvmCashAmountHierarchyDifference")
    public Result replaceCengJiDatasourceSwAuTvmCashAmountHierarchyDifference(SwAuTvmAmountDefference swAuTvmAmountDefference){
        Result result=new Result(ResultDetailMsg.OK);
        try {
            SwAuTvmAmountDefference swAuTvmAmountDefference1 = swAuTvmAmountDefferenceMapper.selectById(swAuTvmAmountDefference.getId());
            if(swAuTvmAmountDefference.getDataSource().equals("1")){ //选择结账单据
//                BigDecimal tvmBillReceivePapaer = swAuTvmAmountDefference1.getTvmBillReceivePapaer(); tvmBillReceivePapaer=tvmBillReceivePapaer==null?new BigDecimal(0):tvmBillReceivePapaer;
//                BigDecimal tvmBillReceiveCoins = swAuTvmAmountDefference1.getTvmBillReceiveCoins();tvmBillReceiveCoins=tvmBillReceiveCoins==null?new BigDecimal(0):tvmBillReceiveCoins;
//                BigDecimal tvmBillNoteChange = swAuTvmAmountDefference1.getTvmBillNoteChange(); tvmBillNoteChange=tvmBillNoteChange==null?new BigDecimal(0):tvmBillNoteChange;
//                BigDecimal tvmBillCoinChange = swAuTvmAmountDefference1.getTvmBillCoinChange();tvmBillCoinChange=tvmBillCoinChange==null?new BigDecimal(0):tvmBillCoinChange;
                BigDecimal tvmBillCashSellTicket = swAuTvmAmountDefference1.getTvmBillCashSellTicket(); tvmBillCashSellTicket=tvmBillCashSellTicket==null?new BigDecimal(0):tvmBillCashSellTicket;
                BigDecimal tvmBillCashRecharge = swAuTvmAmountDefference1.getTvmBillCashRecharge();tvmBillCashRecharge=tvmBillCashRecharge==null?new BigDecimal(0):tvmBillCashRecharge;
                BigDecimal tvmBillCashReturn = swAuTvmAmountDefference1.getTvmBillCashReturn(); tvmBillCashReturn=tvmBillCashReturn==null?new BigDecimal(0):tvmBillCashReturn;
                BigDecimal actualMoney = swAuTvmAmountDefference1.getActualMoney(); actualMoney=actualMoney==null?new BigDecimal(0):actualMoney;
//                BigDecimal subtract = (swAuTvmAmountDefference1.getTvmBillReceivePapaer().add(swAuTvmAmountDefference1.getTvmBillReceiveCoins())).subtract((swAuTvmAmountDefference1.getTvmBillNoteChange().add(swAuTvmAmountDefference1.getTvmBillCoinChange())));
                //BigDecimal subtract = tvmBillReceivePapaer.add(tvmBillReceiveCoins).subtract(tvmBillNoteChange).subtract(tvmBillCoinChange);
                BigDecimal add = tvmBillCashSellTicket.add(tvmBillCashRecharge).add(tvmBillCashReturn);
                BigDecimal subtract = actualMoney.subtract(tvmBillCashSellTicket).subtract(tvmBillCashRecharge).subtract(tvmBillCashReturn);
                swAuTvmAmountDefference.setSystemMoney(add);
                swAuTvmAmountDefference.setDiffMoney(subtract);
            }else if(swAuTvmAmountDefference.getDataSource().equals("2")){ //选择sc
                BigDecimal scCashSellTicket = swAuTvmAmountDefference1.getScCashSellTicket();scCashSellTicket=scCashSellTicket==null?new BigDecimal(0):scCashSellTicket;
                BigDecimal scCashRecharge = swAuTvmAmountDefference1.getScCashRecharge();scCashRecharge=scCashRecharge==null?new BigDecimal(0):scCashRecharge;
                BigDecimal scCashReturn = swAuTvmAmountDefference1.getScCashReturn();scCashReturn=scCashReturn==null?new BigDecimal(0):scCashReturn;
                BigDecimal subtract = scCashSellTicket.add(scCashRecharge).add(scCashReturn);
//                BigDecimal subtract = swAuTvmAmountDefference1.getScCashSellTicket().add(swAuTvmAmountDefference1.getScCashRecharge()).subtract(swAuTvmAmountDefference1.getScCashReturn());
                swAuTvmAmountDefference.setSystemMoney(subtract);
            }else if(swAuTvmAmountDefference.getDataSource().equals("3")){//选择lc
                BigDecimal lcCashSellTicket = swAuTvmAmountDefference1.getLcCashSellTicket();lcCashSellTicket=lcCashSellTicket==null?new BigDecimal(0):lcCashSellTicket;
                BigDecimal lcCashRecharge = swAuTvmAmountDefference1.getLcCashRecharge();lcCashRecharge=lcCashRecharge==null?new BigDecimal(0):lcCashRecharge;
                BigDecimal lcCashReturn = swAuTvmAmountDefference1.getLcCashReturn();lcCashReturn=lcCashReturn==null?new BigDecimal(0):lcCashReturn;
                BigDecimal subtract = lcCashSellTicket.add(lcCashRecharge).add(lcCashReturn);

//                BigDecimal subtract = swAuTvmAmountDefference1.getLcCashSellTicket().add(swAuTvmAmountDefference1.getLcCashRecharge()).subtract(swAuTvmAmountDefference1.getLcCashReturn());
                swAuTvmAmountDefference.setSystemMoney(subtract);
            }else if(swAuTvmAmountDefference.getDataSource().equals("4")){//选择ACCc
                BigDecimal accCashSellTicket = swAuTvmAmountDefference1.getAccCashSellTicket();accCashSellTicket=accCashSellTicket==null?new BigDecimal(0):accCashSellTicket;
                BigDecimal accCashRecharge = swAuTvmAmountDefference1.getAccCashRecharge();accCashRecharge=accCashRecharge==null?new BigDecimal(0):accCashRecharge;
                BigDecimal accCashReturn = swAuTvmAmountDefference1.getAccCashReturn();accCashReturn=accCashReturn==null?new BigDecimal(0):accCashReturn;
                BigDecimal subtract = accCashSellTicket.add(accCashRecharge).add(accCashReturn);

//                BigDecimal subtract = swAuTvmAmountDefference1.getAccCashSellTicket().add(swAuTvmAmountDefference1.getAccCashRecharge()).subtract(swAuTvmAmountDefference1.getAccCashReturn());
                swAuTvmAmountDefference.setSystemMoney(subtract);
            }else if(swAuTvmAmountDefference.getDataSource().equals("5")){
                BigDecimal singleDeviceSysMoney = swAuTvmAmountDefference1.getSingleDeviceSysMoney();
                swAuTvmAmountDefference.setSystemMoney(singleDeviceSysMoney);
            }else if(swAuTvmAmountDefference.getDataSource().equals("6")){
                BigDecimal singleDeviceSysMoney = swAuTvmAmountDefference1.getBoxAuditSysMoney();
                swAuTvmAmountDefference.setSystemMoney(singleDeviceSysMoney);
            }
            //系统金额
            BigDecimal systemAmount = swAuTvmAmountDefference.getSystemMoney() == null ? swAuTvmAmountDefference1.getSystemMoney() : swAuTvmAmountDefference.getSystemMoney();
            BigDecimal diffMoney=swAuTvmAmountDefference1.getActualMoney().subtract(systemAmount);
//            swAuTvmAmountDefference.setDiffMoney(swAuTvmAmountDefference1.getSystemMoney().subtract(swAuTvmAmountDefference1.getActualMoney().subtract(swAuTvmAmountDefference1.getSupplementMoney().add(swAuTvmAmountDefference1.getHandOutMoney()))));
            swAuTvmAmountDefference.setDiffMoney(diffMoney);
            swAuTvmAmountDefferenceMapper.updateById(swAuTvmAmountDefference);
        }catch (Exception e){
            log.error("{}",e);
            result.setResult(ResultDetailMsg.CHECK_UPDATE_ERROR);
            result.setMsg("替换失败");
        }
        return result;
    }
    /**

	  TVM票款差异审核---数据来源替换---结账单据查看
	*/
    @ApiOperation(value = "TVM票款差异审核---数据来源替换---结账单据查看",notes = "TVM票款差异审核---数据来源替换---结账单据查看")
    @RequestMapping("/chaKanJieZhangInfo")
    public Result chaKanJieZhangInfo(@RequestParam Map<String,String> param) throws SQLException, ParseException {
        Result result=new Result(ResultDetailMsg.OK);
        String lineCode=param.get("lineCode");
        String stationCode=param.get("stationCode");
        String tvmCode=param.get("tvmCode");
        String incomeSettleBeginTime=param.get("incomeSettleBeginTime")+" 02:00:00";
        Date incomeSettleEndTime1 = DateFormat.panDuanDate(param.get("incomeSettleEndTime"));
        incomeSettleEndTime1=DateFormat.date_add_or_sub_days(incomeSettleEndTime1,1);//加一天
        String incomeSettleEndTime=DateFormat.date_ex_str(incomeSettleEndTime1,"yyyy-MM-dd")+" 01:59:59";
        String sql="SELECT a.tvm_code tvmCode,b.RECEIVE_NOTES receiveNotes," +
                "b.RECEIVE_COIN receiveCoin," +
                "b.NOTE_CHANGEN noteChangen," +
                "b.COIN_CHANGE coinChange," +
                "b.FAULT_REFUND_AMOUNT faultRefundAmount," +
                "b.CHANGE_TOTAL_MONEY changeTotalMoney," +
                "b.RECHARGE_MONEY rechargeMoney," +
                "b.START_TIME startTime," +
                "b.END_TIME endTime," +
                "b.SELL_TICKET_TOTAL_MONEY sellTicketTotalMoney," +
                "b.RECEIVE_TOTAL_MONEY receiveTotalMoney from sw_st_tvm_daily_bill a,sw_st_tvm_daily_bill_cash_pay b  " +
                " where a.id=b.RELATION_ID and a.del_flag='0' and b.del_flag='0'\n" +
                " and  a.DEL_FLAG ='0' and a.line_code='"+lineCode+"' and a.station_code='"+stationCode+"' and a.tvm_code='"+tvmCode+"' " +
                "and (a.START_TIME between '"+incomeSettleBeginTime+"' and '"+incomeSettleEndTime+"') " +
                "and (a.END_TIME between '"+incomeSettleBeginTime+"' and '"+incomeSettleEndTime+"')";
        List<Map<String, Object>> maps = JdbcUtil.exeSqlQuery(sql);
        result.setData(maps);
        return result;
    }


    /**
     * 编辑操作 TVM票款差异审核
     * @param
     * @param swAuTvmAmountDefference
     * @param
     * @return
     */
    @ApiOperation(value = "TVM票款差异审核编辑", notes = "TVM票款差异审核编辑")
    @PostMapping("/updateSwAuTvmAmountDefference")
    @Transactional(rollbackFor = Exception.class)
    public Result updateSwAuTvmAmountDefference(@RequestBody SwAuTvmAmountDefference swAuTvmAmountDefference){
        Result res=new Result(ResultDetailMsg.OK);
        try {

            //修改之前保存记录表 核对数据来源  1.人工修改 2.SC 3.LC 4.ACC 5.单台设备差异协查结果 6.分钱箱审核结果 7.人工修改
            PigxUser user = SecurityUtils.getUser();
            SwAuTvmAmountDefference tvmAmountDifference = swAuTvmAmountDefferenceMapper.selectById(swAuTvmAmountDefference.getId());
            SwAuTvmAmountDefferenceLog tvmAmountDifferenceLog = new SwAuTvmAmountDefferenceLog();
            BeanUtils.copyProperties(tvmAmountDifference,tvmAmountDifferenceLog);

            SwAuTvmAmountDefference newDefference = new SwAuTvmAmountDefference();
            newDefference.setId(tvmAmountDifference.getId());
            //1.人工修改
            if("1".equals(swAuTvmAmountDefference.getDataSource())){
                newDefference.setTvmBillCashSellTicket(swAuTvmAmountDefference.getTvmBillCashSellTicket());
                newDefference.setTvmBillCashRecharge(swAuTvmAmountDefference.getTvmBillCashRecharge());
                newDefference.setTvmBillCashReturn(swAuTvmAmountDefference.getTvmBillCashReturn());
                BigDecimal tvmBillCashSellTicket = swAuTvmAmountDefference.getTvmBillCashSellTicket(); tvmBillCashSellTicket=tvmBillCashSellTicket==null?new BigDecimal(0):tvmBillCashSellTicket;
                BigDecimal tvmBillCashRecharge = swAuTvmAmountDefference.getTvmBillCashRecharge();tvmBillCashRecharge=tvmBillCashRecharge==null?new BigDecimal(0):tvmBillCashRecharge;
                BigDecimal tvmBillCashReturn = swAuTvmAmountDefference.getTvmBillCashReturn(); tvmBillCashReturn=tvmBillCashReturn==null?new BigDecimal(0):tvmBillCashReturn;
                BigDecimal actualMoney = swAuTvmAmountDefference.getActualMoney(); actualMoney=actualMoney==null?new BigDecimal(0):actualMoney;
                BigDecimal add = tvmBillCashSellTicket.add(tvmBillCashRecharge).add(tvmBillCashReturn);
                BigDecimal subtract = actualMoney.subtract(tvmBillCashSellTicket).subtract(tvmBillCashRecharge).subtract(tvmBillCashReturn);
                newDefference.setSystemMoney(add);
                newDefference.setDiffMoney(subtract);
                tvmAmountDifferenceLog.setCashSellTicket(tvmAmountDifference.getTvmBillCashSellTicket());
                tvmAmountDifferenceLog.setCashRecharge(tvmAmountDifference.getTvmBillCashRecharge());
                tvmAmountDifferenceLog.setCashReturn(tvmAmountDifference.getTvmBillCashReturn());
              }
            //2.SC
            if("2".equals(swAuTvmAmountDefference.getDataSource())){
                newDefference.setTvmBillCashSellTicket(swAuTvmAmountDefference.getScCashSellTicket());
                newDefference.setTvmBillCashRecharge(swAuTvmAmountDefference.getScCashRecharge());
                newDefference.setTvmBillCashReturn(swAuTvmAmountDefference.getScCashReturn());
                BigDecimal scCashSellTicket = swAuTvmAmountDefference.getScCashSellTicket();
                scCashSellTicket=scCashSellTicket==null?new BigDecimal(0):scCashSellTicket;

                BigDecimal scCashRecharge = swAuTvmAmountDefference.getScCashRecharge();
                scCashRecharge=scCashRecharge==null?new BigDecimal(0):scCashRecharge;

                BigDecimal tvmBillCashReturn = swAuTvmAmountDefference.getScCashReturn();
                tvmBillCashReturn=tvmBillCashReturn==null?new BigDecimal(0):tvmBillCashReturn;

                BigDecimal actualMoney = swAuTvmAmountDefference.getActualMoney(); actualMoney=actualMoney==null?new BigDecimal(0):actualMoney;
                BigDecimal add = scCashSellTicket.add(scCashRecharge).add(tvmBillCashReturn);
                BigDecimal subtract = actualMoney.subtract(scCashSellTicket).subtract(scCashRecharge).subtract(tvmBillCashReturn);
                newDefference.setSystemMoney(add);
                newDefference.setDiffMoney(subtract);
                tvmAmountDifferenceLog.setCashSellTicket(tvmAmountDifference.getScCashSellTicket());
                tvmAmountDifferenceLog.setCashRecharge(tvmAmountDifference.getScCashRecharge());
                tvmAmountDifferenceLog.setCashReturn(tvmAmountDifference.getScCashReturn());
            }
            //3.LC
            if("3".equals(swAuTvmAmountDefference.getDataSource())){
                newDefference.setTvmBillCashSellTicket(swAuTvmAmountDefference.getLcCashSellTicket());
                newDefference.setTvmBillCashRecharge(swAuTvmAmountDefference.getLcCashRecharge());
                newDefference.setTvmBillCashReturn(swAuTvmAmountDefference.getLcCashReturn());
                BigDecimal lcCashSellTicket = swAuTvmAmountDefference.getLcCashSellTicket();
                lcCashSellTicket=lcCashSellTicket==null?new BigDecimal(0):lcCashSellTicket;

                BigDecimal lcCashRecharge = swAuTvmAmountDefference.getLcCashRecharge();
                lcCashRecharge=lcCashRecharge==null?new BigDecimal(0):lcCashRecharge;

                BigDecimal lcCashReturn = swAuTvmAmountDefference.getLcCashReturn();
                lcCashReturn=lcCashReturn==null?new BigDecimal(0):lcCashReturn;

                BigDecimal actualMoney = swAuTvmAmountDefference.getActualMoney(); actualMoney=actualMoney==null?new BigDecimal(0):actualMoney;
                BigDecimal add = lcCashSellTicket.add(lcCashRecharge).add(lcCashReturn);
                BigDecimal subtract = actualMoney.subtract(lcCashSellTicket).subtract(lcCashRecharge).subtract(lcCashReturn);
                newDefference.setSystemMoney(add);
                newDefference.setDiffMoney(subtract);
                tvmAmountDifferenceLog.setCashSellTicket(tvmAmountDifference.getLcCashSellTicket());
                tvmAmountDifferenceLog.setCashRecharge(tvmAmountDifference.getLcCashRecharge());
                tvmAmountDifferenceLog.setCashReturn(tvmAmountDifference.getLcCashReturn());
            }
            //4.ACC
            if("4".equals(swAuTvmAmountDefference.getDataSource())){
                newDefference.setTvmBillCashSellTicket(swAuTvmAmountDefference.getAccCashSellTicket());
                newDefference.setTvmBillCashRecharge(swAuTvmAmountDefference.getAccCashRecharge());
                newDefference.setTvmBillCashReturn(swAuTvmAmountDefference.getAccCashReturn());
                BigDecimal accCashSellTicket = swAuTvmAmountDefference.getAccCashSellTicket();
                accCashSellTicket=accCashSellTicket==null?new BigDecimal(0):accCashSellTicket;

                BigDecimal accCashRecharge = swAuTvmAmountDefference.getAccCashRecharge();
                accCashRecharge=accCashRecharge==null?new BigDecimal(0):accCashRecharge;

                BigDecimal accCashReturn = swAuTvmAmountDefference.getAccCashReturn();
                accCashReturn=accCashReturn==null?new BigDecimal(0):accCashReturn;

                BigDecimal actualMoney = swAuTvmAmountDefference.getActualMoney(); actualMoney=actualMoney==null?new BigDecimal(0):actualMoney;
                BigDecimal add = accCashSellTicket.add(accCashRecharge).add(accCashReturn);
                BigDecimal subtract = actualMoney.subtract(accCashSellTicket).subtract(accCashRecharge).subtract(accCashReturn);
                newDefference.setSystemMoney(add);
                newDefference.setDiffMoney(subtract);
                tvmAmountDifferenceLog.setCashSellTicket(tvmAmountDifference.getAccCashSellTicket());
                tvmAmountDifferenceLog.setCashRecharge(tvmAmountDifference.getAccCashRecharge());
                tvmAmountDifferenceLog.setCashReturn(tvmAmountDifference.getAccCashReturn());
            }
            tvmAmountDifferenceLog.setRelationId(tvmAmountDifference.getId());
            tvmAmountDifferenceLog.setCreatorId(user.getUserCode());
            tvmAmountDifferenceLog.setCreatorName(user.getNikeName());
            tvmAmountDifferenceLog.setCreateTime(new Date());
            tvmAmountDifferenceLog.setReasonRemark(tvmAmountDifference.getReasonRemark());
            int b = swAuTvmAmountDefferenceLogMapper.insert(tvmAmountDifferenceLog);
            if(b>0){
                //人工修改
                newDefference.setDataSource("1");
                newDefference.setReasonRemark(swAuTvmAmountDefference.getReasonRemark());
                swAuTvmAmountDefferenceMapper.updateById(newDefference);
            }
        }catch (Exception e){
            log.error("{}",e);
            res.setResult(ResultDetailMsg.CHECK_UPDATE_ERROR);
            res.setMsg("TVM票款编辑失败");
        }
        return res;
    }


    /**
     * 查询日志记录表
     * @return
     */
    @GetMapping("/SwAuTvmAmountDefferenceLogIdList/{id}/{dataSource}")
    @ApiOperation(value = "查询记录表",notes = "查询记录表")
    public Result SwAuTvmAmountDefferenceLogIdList(
            @PathVariable (value = "id") Integer relationId
    ){
        Result res=new Result(ResultDetailMsg.OK);
        try {
            res.setData(swAuTvmAmountDefferenceLogMapper.selectList(Wrappers.<SwAuTvmAmountDefferenceLog>lambdaQuery()
                    .eq(SwAuTvmAmountDefferenceLog::getRelationId,relationId)));
        }catch (Exception e){
            log.error("{}",e);
            res.setResult(ResultDetailMsg.CHECK_SELECT_ERROR);
            res.setMsg("查询失败");
        }
        return res;
    }

    /**
     * 通过id列表撤回审核通过的TVM票款差异审核主页,2021012023  调整为只更新审核状态，审核人和审核日期不置空
     * @param ids ids
     * @return R
     */
    @ApiOperation(value = "通过id列表撤回审核通过的TVM票款差异审核主页", notes = "通过id列表撤回审核通过的TVM票款差异审核主页")
    @SysLog("通过id列表撤回审核通过的TVM票款差异审核主页" )
    @PutMapping("/revokeTvmIds")
    public R revokeIds(@RequestParam(value = "ids") List<Integer> ids) {
        LambdaUpdateWrapper<FareDifferencesInAudit> lambdaUpdateWrapper = Wrappers.<FareDifferencesInAudit>lambdaUpdate()
                .set(FareDifferencesInAudit::getAuditStatus, "0")//撤回审核状态为0
                //.set(FareDifferencesInAudit::getAuditTime, null)
                //.set(FareDifferencesInAudit::getAuditPersonCode, null)
                //.set(FareDifferencesInAudit::getAuditPersonName, null)
                .set(FareDifferencesInAudit::getUpdateTime, new Date())
                .in(FareDifferencesInAudit::getId,ids);
        return R.ok(fareDifferencesInAuditMapper.update(null,lambdaUpdateWrapper));
    }

    /**
     * 作废TVM数据
     * @param param
     * @return
     */
    @ApiOperation(value = "作废TVM数据",notes = "作废TVM数据")
    @RequestMapping("/cancellationTvmDate")
	@SysLog("通过id列表作废TVM票款差异审核主页" )
    public R cancellationTvmDate(@RequestParam Map<String,String> param){
        return R.ok(fareDifferencesInAuditService.invalidTvmData(param));
    }
	  /**
     * 删除重复提交数据
     * @param param
     * @return
     */
    @ApiOperation(value = "删除重复提交数据",notes = "删除重复提交数据")
    @RequestMapping("/delRepeatTvmData")
    public R delRepeatTvmData(@RequestParam(value = "ids") List<Integer> ids,@RequestParam(value = "flag") String flag){

		 log.info("TVM删除 flag 参数======================="+flag);
		 if(ids!=null && ids.size()>0){
			int id = ids.get(0);
			return R.ok(fareDifferencesInAuditService.delRepeatTvmData(id,flag));
        }
		return R.failed("没有选择对应要删除的数据");
    }
}
